package com.forhappy.light3ds8.db;

import java.util.LinkedList;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

import com.forhappy.light3ds8.datatype.DataBasic;
import com.forhappy.light3ds8.datatype.DataReal;

public class LedDBMgr {
	private static final String TAG = "LedDBMgr";
//	Context mContext = null;
	ContentResolver  cr = null;
	public LedDBMgr(Context context) {
		cr = context.getContentResolver();
	}

	public boolean reset(){
		Log.d(TAG, "enter LedDBMgr::clearDB()");
		cr.delete(LedDBContentProvider.URI_DATA_REAL, null, null);
		cr.delete(LedDBContentProvider.URI_DATA_BASIC_INFO, null, null);
		return true;
	}
	public boolean saveToDBBasic(LinkedList<DataBasic> dataBasicList){
		if(null == dataBasicList || dataBasicList.size() == 0){
			Log.e(TAG, "in LedDBMgr::saveToDB()dataBasicList is empty");
			return false;
		} else {
			Log.d(TAG, "enter saveToDBBasic, size:" + dataBasicList.size() );
		}

		for(DataBasic data: dataBasicList){
			cr.insert(LedDBContentProvider.URI_DATA_BASIC_INFO, data.toContentValue());
		}
		return true;
	}

	public boolean saveToDBReal(LinkedList<DataReal> dataRealList){
		if(null == dataRealList || dataRealList.size() == 0){
			Log.e(TAG, "in LedDBMgr::saveToDB()dataBasicList is empty");
			return false;
		}
		for(DataReal data: dataRealList){
			Log.d(TAG, "will insert " + data +" to " + LedDBContentProvider.URI_DATA_REAL );
			cr.delete(LedDBContentProvider.URI_DATA_REAL, "id = ?", new String[]{String.valueOf(data.id)});
			cr.insert(LedDBContentProvider.URI_DATA_REAL, data.toContentValue());
		}
		return true;
	}

	public LinkedList<DataBasic> getDatasBasic(){
		Log.d(TAG, "enter getDatasBasicByIdx()");

		LinkedList<DataBasic> listRet = new LinkedList<DataBasic>();
	    Cursor cursor = cr.query(LedDBContentProvider.URI_DATA_BASIC_INFO,
							new String[]{
							LedDBHelper.ITEM_ID,
							LedDBHelper.ITEM_DATAS,
							LedDBHelper.ITEM_USERNAME,
							LedDBHelper.ITEM_INFO}, null, null, LedDBHelper.ITEM_ID + " asc");
		listRet = DataBasic.getDatas(cursor);
		try{cursor.close();}catch(Exception e){}
		return listRet;
	}
	public String getDatasRealByIdx(int realDataIdx){
		Log.d(TAG, "enter getDatasRealByIdx(realDataIdx:" + realDataIdx + ")");
		Cursor cursor  = cr.query(LedDBContentProvider.URI_DATA_REAL,
							new String[]{ LedDBHelper.ITEM_DATAS}, LedDBHelper.ITEM_ID + " = ?",
							new String[]{String.valueOf(realDataIdx)}, null);
		if(null == cursor || cursor.isAfterLast()){
			Log.e(TAG, "int getDatasRealByIdx, cursor is null!");
			return null;
		}

		if(cursor.moveToNext()){
			String datas = cursor.getString(1);
			Log.d(TAG, "get datas forIdx:" + realDataIdx + ", datas:" + datas);
			cursor.close();
			return datas;
		} else {
			Log.e(TAG, "getDatasRealByIdx moveToNext return false!");
		}
		return null;
	}
}
